package com.kuang.controller;

import com.kuang.pojo.Books;
import com.kuang.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    @Qualifier("BookServiceImpl")
    public BookService bookService;

    /**查询所有书籍页面
     * @param model
     * @return所有书籍信息列表
     */
    @RequestMapping("/allBooks")
public String list(Model model){
        List<Books> list=bookService.queryAllBooks();
        model.addAttribute("list",list);
        return "allBooks";
}

    /**跳转到添加书籍页面
     * @return
     */

@RequestMapping("/toAddBook")
public String toAddBook(){
        return "addBook";
}
@RequestMapping("/addBook")
public String addBook(Books books,Model model){
    System.out.println("成功添加书籍："+books);
    bookService.addBook(books);
    model.addAttribute("QBook",books);
    return "redirect:/book/allBooks";
    //重定向回所有书籍列表页面（重定向可防止表单被重复提交）
}
@RequestMapping("/toUpdate")
public String toUpdate(int id,Model model){
    //这个方法负责跳转功能，同时携带用户要修改的那一条书籍信息
    Books books = bookService.queryBookById(id);
    model.addAttribute("QBook",books);
    return "updateBook";
}
@RequestMapping("/updateBook")
public String updateBook(Books books,Model model){
//修改书籍信息

    bookService.updateBook(books);
    model.addAttribute("QBook",books);
    System.out.println("成功修改书籍："+books+"的信息");
    return "redirect:/book/allBooks";
}
@RequestMapping("/deleteBook/{bookID}")
public String deleteBook(@PathVariable("bookID") int id){
    bookService.deleteBookById(id);
    return "redirect:/book/allBooks";
}
@RequestMapping("/queryBook")
public String queryBook(String queryBookName,Model model){
    Books books = bookService.queryBookName(queryBookName);
  System.err.println("queryBook=>"+books);
    List<Books> list = new ArrayList<Books>();
    list.add(books);
    if (books==null){
        list=bookService.queryAllBooks();
        model.addAttribute("error","相关书籍没有数据！！！");
    }
    model.addAttribute("list",list);
    return "allBooks";
}
}
